<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手写call-apply方法</title>
</head>

<body>

    <script>

        // 手写call方法
        function foo(name, age) {
            console.log(name);
            console.log(age);
            console.log(this);
        }

        Function.prototype.mycall = function (myThis, ...other) {

            myThis = myThis === null || myThis === undefined ? myThis = window : myThis = Object(myThis)

            // 1.将myThis指向到this
            // myThis.fn = this
            Object.defineProperty(myThis, 'fn', {
                writable: false,
                configurable: false,
                enumerable: false,
                value: this
            })
            // 2.执行函数
            myThis.fn(...other)
            // 3.删除fn属性
            delete myThis.fn
        }

        Function.prototype.myapply = function (myThis, other) {
            myThis = myThis === null || myThis === undefined ? myThis = window : myThis = Object(myThis)

            // 1.将myThis指向到this
            // myThis.fn = this
            Object.defineProperty(myThis, 'fn', {
                writable: false,
                configurable: false,
                enumerable: false,
                value: this
            })
            // 2.执行函数
            myThis.fn(...other)
            // 3.删除fn属性
            delete myThis.fn
        }

        foo.mycall(123, '李四', 20);
        foo.myapply(123, ['李四', 20]);

    </script>

</body>

</html>